package com.kws.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.*;
import com.kws.merchant.domain.po.AttentionPo;
import com.kws.merchant.domain.vo.AttentionVo;
import com.kws.merchant.domain.vo.GoodsCollectVo;
import com.kws.merchant.mapper.AttentionMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : zhangbenting
 * @date : 2024/11/2 9:46
 * @Version: 1.0
 */
@Service
public class AttentionServiceImpl extends ServiceImpl<AttentionMapper, AttentionEntity> implements AttentionService {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ServeService serveService;

    @Autowired
    private MerchantScoreService merchantScoreService;
    @Autowired
    private GoodsViewService goodsViewService;

    @Override
    public Page<AttentionVo> getAttentionList(AttentionPo attentionPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        attentionPo.setPageSize((attentionPo.getPageSize() - 1) * attentionPo.getTotalPage());
        Long count = baseMapper.getGoodsAttentionCount(userId,
                attentionPo.getShopName());
        Page<AttentionVo> page = new Page<>(attentionPo.getPageSize(), attentionPo.getTotalPage(), count);
        if (count > 0) {
            List<AttentionVo> attentionList = baseMapper.getGoodsAttentionList(userId,
                    attentionPo.getShopName(), attentionPo.getPageSize(), attentionPo.getTotalPage());
            List<Long> shopsId = attentionList.stream().map(AttentionVo::getAttentionTypeId).collect(Collectors.toList());
            List<Device> deviceList = deviceService.list(Wrappers.<Device>lambdaQuery().in(Device::getMerchantId, shopsId));
            List<MerchantScoreEntity> merchantScore = merchantScoreService.list(Wrappers.<MerchantScoreEntity>lambdaQuery()
                    .in(MerchantScoreEntity::getMerchantId, shopsId));
            Map<Long, List<Device>> listMap = new HashMap<>();
            if (ObjectUtils.isNotNull(deviceList)) {
                listMap = deviceList.stream().collect(Collectors.groupingBy(Device::getMerchantId));
            }
            for (AttentionVo attentionVo : attentionList) {
                List<Device> devices = listMap.get(attentionVo.getAttentionTypeId());
                if (CollectionUtils.isEmpty(devices)) {
                    continue; // 如果 devices 为空或者是空集合，直接跳过本次循环
                }
                List<GoodsCollectVo> goodsCollectVos = new ArrayList<>();
                for (Device device : devices) {
                    if (goodsCollectVos.size() >= 5) {
                        break; // 当 goodsCollectVos 长度达到 5 时跳出循环
                    }
                    GoodsCollectVo goodsCollectVo = new GoodsCollectVo();
                    goodsCollectVo.setImg(FileUtil.fixFileName() + device.getImg());
                    goodsCollectVo.setGoodsId(device.getId());
                    goodsCollectVo.setGoodsName(device.getName());
                    goodsCollectVo.setPrice(device.getPrice());
                    goodsCollectVo.setMerchantId(device.getMerchantId());
                    goodsCollectVos.add(goodsCollectVo);
                }
                // 设置店铺星级
                MerchantScoreEntity merchantScoreEntity = merchantScore.stream().filter(p -> p.getMerchantId().equals(attentionVo.getAttentionTypeId()))
                        .findFirst().orElse(null);
                if (merchantScoreEntity != null) {
                    attentionVo.setStopLevel(merchantScoreEntity.getShopScore());
                } else {
                    attentionVo.setStopLevel(0.0);
                }
                attentionVo.setGoodsVoList(goodsCollectVos);
            }
            page.setRecords(attentionList);
            return page;
        }
        return page;
    }

    @Override
    public Page<GoodsCollectVo> getCollectList(AttentionPo attentionPo) {
        attentionPo.setPageSize((attentionPo.getPageSize() - 1) * attentionPo.getTotalPage());
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<AttentionEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AttentionEntity::getUserId, userId);
        wrapper.eq(AttentionEntity::getType, attentionPo.getType());
        long count = this.count(wrapper);
        Page<GoodsCollectVo> page = new Page<>(attentionPo.getTotalPage(), attentionPo.getTotalPage(), count);
        if (count > 0) {
            if (attentionPo.getType().equals("0")) {
                List<GoodsCollectVo> shopsCollectList = baseMapper.getDeviceCollectList(userId,
                        attentionPo.getPageSize(), attentionPo.getTotalPage());
                for (GoodsCollectVo goodsCollectVo : shopsCollectList) {
                    goodsCollectVo.setGoodsType(0);
                    goodsCollectVo.setImg(FileUtil.fixFileName() + goodsCollectVo.getImg());
                }
                page.setRecords(shopsCollectList);
                return page;
            } else if (attentionPo.getType().equals("1")) {
                List<GoodsCollectVo> shopsCollectList = baseMapper.getServeCollectList(userId,
                        attentionPo.getPageSize(), attentionPo.getTotalPage());
                for (GoodsCollectVo goodsCollectVo : shopsCollectList) {
                    goodsCollectVo.setGoodsType(1);
                    goodsCollectVo.setImg(FileUtil.fixFileName() + goodsCollectVo.getImg());
                }
                page.setRecords(shopsCollectList);
                return page;

            } else {
                throw new ServiceException("关注类型参数错误");
            }
        }
        return null;
    }

    /**
     * 商品收藏
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public Double listCollectByTime(Long userId, String time) {
        return this.baseMapper.listCollectByTime(userId, time);
    }

    /**
     * 根据时间查询收藏人数
     *
     * @param userId
     * @param time
     * @return
     */
    @Override
    public Double listCollectPersonByTime(Long userId, String time) {
        return this.baseMapper.listCollectPersonByTime(userId, time);
    }

    @Override
    public boolean isAttention(AttentionPo attentionPo) {
        if (attentionPo == null || CollectionUtils.isEmpty(attentionPo.getAttentionTypeIds()) || StringUtils.isEmpty(attentionPo.getType())) {
            // 参数为空或不合法抛出异常
            throw new ServiceException("收藏类型或者收藏类型ID不能为空！");
        }
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        List<Long> attentionIds = attentionPo.getAttentionTypeIds();
        String type = attentionPo.getType();

        LambdaQueryWrapper<AttentionEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AttentionEntity::getUserId, userId)
                .eq(AttentionEntity::getType, type)
                .in(AttentionEntity::getAttentionTypeId, attentionIds);

        return ObjectUtils.isNotNull(this.getOne(wrapper));
    }

    @Override
    public boolean cancelAttentionShopCartGoods(AttentionPo attentionPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        if (attentionPo.getAttentionIds() != null && attentionPo.getAttentionIds().size() > 0) {
            return this.removeByIds(attentionPo.getAttentionIds());
        }
        if (attentionPo == null || CollectionUtils.isEmpty(attentionPo.getAttentionTypeIds()) || StringUtils.isEmpty(attentionPo.getType())) {
            // 参数为空或不合法抛出异常
            throw new ServiceException("收藏类型或者收藏类型ID不能为空！");
        }
        LambdaQueryWrapper<AttentionEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AttentionEntity::getUserId, userId);
        wrapper.eq(AttentionEntity::getType, attentionPo.getType());
        wrapper.in(AttentionEntity::getAttentionTypeId, attentionPo.getAttentionTypeIds());
        return this.remove(wrapper);
    }

    /**
     * 总商品收藏
     * @param userId
     * @return
     */
    @Override
    public Double countCollect(Long userId) {
        return this.baseMapper.countCollect(userId);
    }

    /**
     * 总收藏人数
     * @param userId
     * @return
     */
    @Override
    public Double countCollectPerson(Long userId) {
        return this.baseMapper.countCollectPerson(userId);
    }

    @Override
    public Object updateGoodsView(Long goodsViewId, Long time) {
        GoodsView goodsView = goodsViewService.getById(goodsViewId);
        if (ObjectUtils.isEmpty(goodsView)){
            throw new RuntimeException("浏览数据为空");
        }
        goodsView.setViewTime(time);
        return goodsViewService.updateById(goodsView);
    }


    @Override
    public boolean attentionShopCartGoods(AttentionPo attentionPo) {
        if (attentionPo == null || CollectionUtils.isEmpty(attentionPo.getAttentionTypeIds()) || StringUtils.isEmpty(attentionPo.getType())) {
            // 参数为空或不合法抛出异常
            throw new ServiceException("收藏类型或者收藏类型ID不能为空！");
        }
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        List<Long> attentionTypeIds = attentionPo.getAttentionTypeIds();
        ArrayList<AttentionEntity> attentionEntities = new ArrayList<>();
        // 查询已存在的记录
        List<AttentionEntity> existingEntities = getExistingAttentionEntities(userId, attentionTypeIds);
        for (Long attentionTypeId : attentionTypeIds) {
            AttentionEntity attentionEntity = new AttentionEntity();
            attentionEntity.setAttentionTypeId(attentionTypeId);
            attentionEntity.setUserId(SecurityUtils.getUserId());
            attentionEntity.setType(attentionPo.getType());
            //用于统计商家商品、服务收藏情况
            switch (attentionPo.getType()) {
                case "0":
                    Device device = deviceService.getById(attentionTypeId);
                    if (ObjectUtils.isEmpty(device)) {
                        throw new RuntimeException("没有查询到该设备信息");
                    }
                    attentionEntity.setMerchantId(device.getMerchantId());
                    break;
                case "1":
                    Serve serve = serveService.getById(attentionTypeId);
                    if (ObjectUtils.isEmpty(serve)) {
                        throw new RuntimeException("没有查询到该服务信息");
                    }
                    attentionEntity.setMerchantId(serve.getMerchantId());
                    break;
            }
            //判断更新逻辑
            AttentionEntity attention = existingEntities.stream().filter(p -> p.getAttentionTypeId() != null
                    && p.getAttentionTypeId().equals(attentionTypeId)).findFirst().orElse(null);
            if (ObjectUtils.isNotNull(attention)) {
                attentionEntity.setId(attention.getId());
            }
            attentionEntities.add(attentionEntity);
        }
        return saveOrUpdateBatch(attentionEntities);
    }

    private List<AttentionEntity> getExistingAttentionEntities(Long userId, List<Long> attentionTypeIds) {
        LambdaQueryWrapper<AttentionEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AttentionEntity::getUserId, userId);
        wrapper.in(AttentionEntity::getAttentionTypeId, attentionTypeIds);
        return this.list(wrapper);
    }
}
